package com.af.community.smart.business

import android.annotation.SuppressLint
import android.os.Bundle
import com.af.community.smart.base.BaseActivity
import com.af.community.smart.base.getString
import com.af.community.smart.base.loadCircleImage
import com.af.community.smart.base.oneClick
import com.af.community.smart.utils.*
import com.af.community.smart.viewmodel.SignViewModel
import com.baidu.mapapi.BDLocationHelper
import kotlinx.android.synthetic.main.activity_sign.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class SignActivity : BaseActivity() {

    private var mAddress: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sign)
        initTitle(title = "考勤签到", name = "历史记录")

        BDLocationHelper.getInstance(baseContext)
            .setDuration(10000)
            .startLocation(200) { location, isDone, codes ->
                if (200 in codes && isDone) {
                    val poiList = location.poiList
                    if (poiList.isNotEmpty()) mAddress = poiList[0].name
                    if (mAddress.isEmpty()) mAddress = location.addrStr
                    sign_addr.text = mAddress
                }
            }
    }

    override fun getViewModel() = getViewModel<SignViewModel>()

    @SuppressLint("SetTextI18n")
    override fun initTitle(title: String, name: String) {
        super.initTitle(title, name)
        sign_name.text = "${getString("userName")}（网格员）"
        sign_img.loadCircleImage(getString("avatar").scaleImage())

        var currentValue = System.currentTimeMillis()
        sign_time.text = "当前时间：${currentValue.getTimeString()}"
        getViewModel().startCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBy(
                onNext = {
                    currentValue += 1000
                    val timeValue = "当前时间：${currentValue.getTimeString()}"
                    sign_time.text = timeValue
                }
            )

        tvRight?.oneClick { startActivity<SignListActivity>() }
        bt_sign.oneClick {
            if (mAddress.isEmpty()) {
                toast("位置信息获取失败，请检查网络！")
                return@oneClick
            }

            getViewModel().getSignData(
                "userId" to getString("userId"),
                "address" to mAddress
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        toast("签到成功！")
                        getData()
                    }
                )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        BDLocationHelper.getInstance(baseContext).stopLocation()
        BDLocationHelper.getInstance(baseContext).removeCode(200)
    }

}
